<template>
  <div class="product-publish-container">
    <el-card class="publish-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2 class="title">农产品发布</h2>
          <div class="header-actions">
            <el-button @click="resetForm">重置表单</el-button>
            <el-button type="primary" :loading="submitting" @click="submitForm">
              立即发布
              <template #icon>
                <el-icon>
                  <Upload />
                </el-icon>
              </template>
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-position="top"
        class="smart-form"
      >
        <el-row :gutter="30">
          <!-- 左侧表单 -->
          <el-col :span="14">
            <el-form-item prop="categoryId">
              <el-select
                style="margin-bottom: 20px"
                v-model="formData.categoryId"
                placeholder="请选择商品分类"
                class="category-select"
                filterable
                loading-text="加载中..."
                :loading="categoryLoading"
              >
                <el-option
                  v-for="item in categories"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId"
                >
                  <div class="category-option">
                    <span class="category-name">{{ item.categoryName }}</span>
                    <!--                    <span class="category-id">ID: {{ item.categoryId }}</span>-->
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="title">
              <el-input
                style="margin-bottom: 20px"
                v-model="formData.title"
                placeholder="请输入商品标题，建议包含产地和特色"
                clearable
                class="title-input"
              >
                <template #prefix>
                  <el-icon>
                    <Goods />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="description">
              <el-input
                style="margin-bottom: 20px"
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入商品详细描述，包括品种、规格、产地等信息"
                maxlength="200"
                show-word-limit
                class="desc-textarea"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="price">
                  <el-input-number
                    style="margin-bottom: 20px"
                    v-model="formData.price"
                    :min="0"
                    :precision="2"
                    :step="1"
                    controls-position="right"
                    class="full-width price-input"
                  >
                    <template #prefix>
                      <span class="currency-symbol">¥</span>
                    </template>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="stock">
                  <el-input-number
                    style="margin-bottom: 20px"
                    v-model="formData.stock"
                    :min="0"
                    :step="10"
                    controls-position="right"
                    class="full-width stock-input"
                  >
                    <template #suffix>
                      <span class="unit">件</span>
                    </template>
                  </el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <!-- 右侧图片上传 -->
          <el-col :span="10">
            <el-form-item label="商品主图" prop="coverImage">
              <el-upload
                style="width: 400px; margin-top: -40px; margin-left: 50px"
                class="cover-uploader"
                :class="{ 'upload-loading': uploadLoading }"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleCoverChange"
                :disabled="uploadLoading"
                drag
              >
                <template #trigger>
                  <div class="upload-content">
                    <img
                      v-if="formData.coverImage"
                      :src="formData.coverImage"
                      class="cover-image"
                    />
                    <div v-else class="uploader-placeholder">
                      <template v-if="!uploadLoading">
                        <el-icon class="upload-icon">
                          <Picture />
                        </el-icon>
                        <div class="upload-text">点击或拖拽上传主图</div>
                        <div class="upload-hint">
                          建议尺寸：800x800px，JPG/PNG格式
                        </div>
                      </template>
                      <div v-else class="upload-loading-text">
                        <el-icon class="loading-icon">
                          <Loading />
                        </el-icon>
                        图片上传中...
                      </div>
                    </div>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Upload, Goods, Picture } from "@element-plus/icons-vue";
import {
  FileControllerService,
  ProductCategoryControllerService,
  ProductControllerService,
} from "@/generated";

// 表单数据
const formData = reactive({
  categoryId: "",
  title: "",
  description: "",
  price: 0,
  stock: 0,
  coverImage: "",
});

// 分类数据
const categories = ref([]);
const categoryLoading = ref(true);
const uploadLoading = ref(false); // 新增上传加载状态

// 获取分类数据
const loadCategories = async () => {
  try {
    categoryLoading.value = true;
    const res = await ProductCategoryControllerService.getProductCategoryList();

    // 确保接口返回的数据格式正确
    if (res.code === 0 && res.data) {
      categories.value = res.data
        .filter((item) => item.isDeleted === 0) // 过滤已删除的分类
        .sort((a, b) => a.categoryId - b.categoryId); // 按分类ID排序
    } else {
      console.error("分类数据加载失败：", res.message || "未知错误");
      ElMessage.error("分类数据加载失败，请稍后重试");
    }
  } catch (error) {
    console.error("分类加载失败：", error);
    ElMessage.error("分类加载失败，请检查网络或联系管理员");
  } finally {
    categoryLoading.value = false;
  }
};

// 表单验证规则
const formRules = reactive({
  categoryId: [
    { required: true, message: "请选择商品分类", trigger: "change" },
  ],
  title: [
    { required: true, message: "请输入商品标题", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入商品描述", trigger: "blur" },
    { min: 10, max: 200, message: "长度在 10 到 200 个字符", trigger: "blur" },
  ],
  price: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
    { type: "number", min: 0.01, message: "价格必须大于0", trigger: "blur" },
  ],
  stock: [
    { required: true, message: "请输入库存数量", trigger: "blur" },
    { type: "number", min: 1, message: "库存必须大于0", trigger: "blur" },
  ],
});

// 修改后的图片上传处理
const handleCoverChange = async (file) => {
  try {
    uploadLoading.value = true;

    // 1. 验证文件
    const isImage = file.raw.type.includes("image/");
    const isLt5M = file.raw.size / 1024 / 1024 < 5;

    if (!isImage) {
      ElMessage.error("只能上传图片文件!");
      return false;
    }
    if (!isLt5M) {
      ElMessage.error("图片大小不能超过5MB!");
      return false;
    }

    // 2. 创建FormData（重命名变量避免冲突）
    const uploadFormData = new FormData();
    uploadFormData.append("file", file.raw);

    // 3. 调用上传接口
    const res = await FileControllerService.uploadFile(uploadFormData);
    console.log("上传结果:", res);

    if (res.code === 0 && res.data) {
      // 4. 将服务器返回的URL赋值给表单（这里要修改外层的formData）
      formData.coverImage = res.data; // 这里之前错误地使用了局部变量formData
      console.log("上传成功", formData.coverImage);
      ElMessage.success("图片上传成功");
    } else {
      ElMessage.error(res.message || "图片上传失败");
    }
  } catch (error) {
    console.error("上传失败:", error);
    ElMessage.error("图片上传失败，请重试");
  } finally {
    uploadLoading.value = false;
  }
};

// 表单提交
const submitting = ref(false);
const formRef = ref();

// 修改后的表单提交
const submitForm = async () => {
  console.log("提交表单", formData);
  try {
    // 1. 验证表单
    await formRef.value.validate();

    // 2. 检查图片是否已上传
    if (!formData.coverImage) {
      ElMessage.warning("请先上传商品图片");
      return;
    }

    // 3. 准备提交数据
    const submitData = {
      ...formData,
      price: Number(formData.price),
      stock: Number(formData.stock),
    };

    submitting.value = true;

    // 4. 调用商品创建接口
    const res = await ProductControllerService.addProduct(submitData);

    if (res.code === 0) {
      ElMessage.success("商品发布成功!");
      formRef.value.resetFields();
      formData.coverImage = ""; // 重置图片
    } else {
      ElMessage.error(res.message || "商品发布失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请检查表单");
  } finally {
    submitting.value = false;
  }
};

// 页面加载时获取分类数据
onMounted(() => {
  loadCategories();
});
</script>

<style scoped>
.product-publish-container {
  max-width: 1280px;
  margin: 40px auto;
  padding: 0 20px;
}

.publish-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.title {
  margin: 0;
  color: #1a1a1a;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: 1px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 分类选择器优化 */
.category-select {
  width: 100%;
}

.category-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
}

.category-name {
  font-size: 14px;
  color: #333;
}

.category-id {
  font-size: 12px;
  color: #999;
}

/* 输入框优化 */
.title-input {
  :deep(.el-input__inner) {
    padding-left: 36px;
  }

  .el-icon {
    color: var(--el-color-primary);
    font-size: 18px;
    margin-left: 8px;
  }
}

.desc-textarea {
  :deep(.el-textarea__inner) {
    line-height: 1.6;
    font-family: inherit;
  }
}

/* 价格输入优化 */
.price-input {
  :deep(.el-input__prefix) {
    display: flex;
    align-items: center;
    left: 12px;
  }

  .currency-symbol {
    color: #ff6b6b;
    font-weight: 500;
  }
}

.stock-input {
  :deep(.el-input__suffix) {
    display: flex;
    align-items: center;
    right: 12px;
  }

  .unit {
    color: #666;
    font-size: 14px;
  }
}

/* 图片上传优化 */
.cover-uploader {
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-upload) {
    width: 100%;
  }

  .upload-content {
    width: 100%;
    position: relative;
  }
}

.cover-image {
  width: 100%;
  height: 380px;
  object-fit: cover;
  border-radius: 12px;
  transition: transform 0.3s;

  &:hover {
    transform: scale(1.02);
  }
}

.uploader-placeholder {
  height: 380px;
  background: #f8f9fa;
  border: 2px dashed var(--el-border-color);
  border-radius: 12px;
  transition: border-color 0.3s;

  &:hover {
    border-color: var(--el-color-primary);
  }
}

.upload-icon {
  color: var(--el-color-primary);
  font-size: 48px;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #444;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

.upload-tip {
  margin-top: 12px;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 6px;
}

@media (max-width: 768px) {
  .publish-card {
    margin: 0 -20px;
    border-radius: 0;
  }

  .cover-image,
  .uploader-placeholder {
    height: 260px;
  }

  .upload-loading .el-upload-dragger {
    cursor: wait;
  }

  .upload-loading-text {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: var(--el-color-primary);
  }

  .loading-icon {
    font-size: 40px;
    margin-bottom: 10px;
    animation: rotating 2s linear infinite;
  }

  @keyframes rotating {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
}
</style>
